package com.github.bobjoy.java.collection;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;

public class ListDemo {

    private List<Integer> list = new ArrayList<>();
    private List<Integer> link = new LinkedList<>();

    @Before
    public void init() {
        int MAX = 1000000000;
        for (int i = 0; i < MAX; i++) {
            list.add(i);
            link.add(i);
        }
    }

    @After
    public void clear() {
        list.clear();
        link.clear();

        list = null;
        link = null;
    }

    @Test
    public void testAddRemove() {

        long start = System.currentTimeMillis();
        list.remove(9999);
        System.out.println("ArrayList随机删除耗时：" + (System.currentTimeMillis() - start) + "ms");

        start = System.currentTimeMillis();
        list.remove(list.size() - 1);
        System.out.println("ArrayList尾删除耗时：" + (System.currentTimeMillis() - start) + "ms");

        start = System.currentTimeMillis();
        link.remove(9999);
        System.out.println("LinkedList增删耗时：" + (System.currentTimeMillis() - start) + "ms");

    }

    @Test
    public void testGet() {
        long start = System.currentTimeMillis();
        list.get(9999);
        System.out.println("ArrayList查找耗时：" + (System.currentTimeMillis() - start) + "ms");

        start = System.currentTimeMillis();
        link.get(9999);
        System.out.println("LinkedList查找耗时：" + (System.currentTimeMillis() - start) + "ms");
    }

    @Test
    public void testModify() {

        //for (Integer i : list) list.remove(i);

        for(int i = 0; i<list.size(); i++) if(i % 3 == 0) list.remove(i);

        ListIterator<Integer> it = list.listIterator();
        while (it.hasNext()) {
            if (it.next() % 5 == 0) {
                it.remove();
            }
        }
    }

}
